<?php

namespace App\Controllers;

use Framework\Database;
use Framework\Validation;
use Framework\Session;

class UserController 
{
    protected $db;
    
    public function __construct()
    {
        $config = require basePath('config/db.php');
        $this->db = new Database($config);
    }

    /**
     * 显示登陆页面
     * 此方法加载登录试图
     * 
     * @return void
     */
    public function login()
    {
        //调用loadView 函数加载登录页面的试图
        loadView('users/login');
    }

    /**
     * 显示注册页面
     * 此方法加载注册页面
     */
    public function create()
    {
        //调用 loadView 函数来加载创建用户注册页面
        loadview('users/create');
    }

    /**
     * 将用户数据存储到数据库中
     */
    public function store()
    {
        //从POST 请求用户数据
        $name = $_POST['name'];
        $email = $_POST['email'];
        $city = $_POST['city'];
        $province = $_POST['province'];
        $password = $_POST['password'];
        $passwordConfirmation = $_POST['password_confirmation'];
        
        //初始化一个错误的
        $errers = [];
        
        if (!Validation::email($email))
        {
            $errors['email'] = '请输入一个合法的电子邮箱地址!';
        }
        
        if (!Validation::string($name,2,50)){
            $errors['name'] = '姓名长度为2到50!';
        }
        
        if (!Validation::string($password,6,50))
        {
            $errors['password'] = '密码长度为至少6位!';
        }
        
        if (!Validation::match($password, $passwordConfirmation)) 
        {
            $errorsl['password_confirmation'] = '再次的输入密码不一致!';
        }

        //检查是否存在错误
        if (!empty($errors)) {
            loadView('users/create',[
                'errors' => $errors,
                'user'=> [
                    'name' => $name,
                    'email' => $email,
                    'city' => $city,
                    'province' => $province,
                ]
            ]);
            //终止进一步执行
            exit;
        }else{
            //检查电子邮件是否存在
            $params = [
                'email'=> $email 
            ];
                
            $user = $this->db->query('SELECT * FROM users WHERE email = :email', $params)->fetch();

            if ($user)
            {
                $errors['email'] = '该邮箱已注册!';
                loadView('users/create',[
                'errors' => $errors
                ]);
                exit;
            }
                
            //创建用户账号
            $params = [
                'name' => $name,
                'email' => $email,
                'city' => $city,
                'province' => $province,
                'password' => password_hash($password, PASSWORD_DEFAULT)
            ];

            //执行SQL语句
            $this->db->query('INSERT INTO users (name, email, city, province, password) VALUES (:name, :email, :city,
            :province, :password)',$params);

            //GET new user ID
            $userId = $this->db->conn->lastInsertId();

            Session::set('user',[
                'id' => $userId,
                'name' => $name,
                'email' => $email,
                'city' => $city,
                'province' => $province,
            ]);

            //成功后重定向到首页
            redirect('/');
        }
    }

    /**
     * 注销用户并结束会话
     */
    public function logout()
    {
        Session::clearAll();
        
        $params = session_get_cookie_params();
        
        setcookie('PHPSESSID', '', time() - 86400, $params['path'], $params['domain']);
        //重新定向回网站
        redirect('/');
    }

    /**
     * 使用电子邮件和密码验证用户身份
     */
    public function authenticate()
    {
        //从 POST 数据中获取邮件和密码
        $email = $_POST['email'];
        $password = $_POST['password'];
        
        $errors = [];
        
        //验证电子邮件格式
        if (!Validation::email($email))
        {
            $errors['email'] = '请输入合法的邮箱地址! ';
        }
        
        //验证密码长度
        if(!Validation::string($password,6,50))
        {
            $errors['password']='密码为至少6位! ';
        }
        
        //如果存在验证错误，重新加载登录页面并显示
        if (!empty($errors))
        {
            loadView('users/login', [
                'errors'=> $errors
            ]);
            exit;
        }

        //准备查询参数
        $params = [
            'email' => $email
        ];

        //从数据库查询用户
        $user = $this->db->query('SELECT * FROM users WHERE email = :email', $params)->fetch();
        
        if (!$user)
        {
            $errors['email'] = '用户不存在或密码错误!';
            loadView('users/login', [
                'errors'=> $errors
            ]);
            exit;
        }
        
        if(!password_verify($password, $user->password))
        {
            $errors['email'] = '用户不存在或密码错误!';
            loadView('users/login',[
            'errors'=> $errors
        ]);
        exit;
    }
    
    Session::set('user', [
        'id' => $user->id,
        'name' => $user->name,
        'email' => $user->email,
        'city' => $user->city,
        'province' => $user->province
    ]);
    
    //登录成功后重定向到首页
    redirect('/');
    }
}